﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using Pay.Token.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Pay.Token.Controllers {
    [AppAuthorize("Member")]
    public class HomeController : GeneralController {
        private IMerchantService _merchantService;
        private IUnitOfWork _unitOfWork;
        private ISettingService _settingService;
        private INoticeService _noticeService;
        private IMerchIntroduceService _merchIntroduceService;
        private IRedRecordService _redRecordService;
        private IAdvertisementService _iAdvertisementService;
        private IOrderService _iOrderService;
        private readonly ISoupTaskService _iSoupTaskService;
        public HomeController(IMerchantService merchantService, IRedRecordService redRecordService, ISettingService settingService, IMerchIntroduceService merchIntroduceService,
            INoticeService noticeService, IAdvertisementService advertisementService, ISoupTaskService iSoupTaskService, IOrderService iOrderService, IUnitOfWork unitOfWork) {
            _merchantService = merchantService;
            _unitOfWork = unitOfWork;
            _settingService = settingService;
            _noticeService = noticeService;
            _merchIntroduceService = merchIntroduceService;
            _redRecordService = redRecordService;
            _iAdvertisementService = advertisementService;
            _iSoupTaskService = iSoupTaskService;
            _iOrderService = iOrderService;
        }
        [AllowAnonymous]
        public ActionResult Index() {
            //string data = "{\"Data\":{\"Name\":\"吴奶强\",\"FacePic\":\"http://verify-img.cn-shanghai.img.aliyun-inc.com/e89edce444bf45c7b8037cd272b08eabOSS.JPG?Expires=1555397185&OSSAccessKeyId=IJ95qE4nJQY6t6Lk&Signature=QYxprY4R5CQaEJiBB9Ilsdy9MUA%3D\",\"IdCardType\":\"identityCard\",\"EthnicGroup\":\"汉\",\"Address\":\"{\\\"address\\\":{\\\"area\\\":{\\\"text\\\":\\\"福安市\\\",\\\"value\\\":\\\"350981\\\",\\\"key\\\":\\\"area\\\"},\\\"province\\\":{\\\"text\\\":\\\"福建省\\\",\\\"value\\\":\\\"350000\\\",\\\"key\\\":\\\"province\\\"},\\\"town\\\":{\\\"value\\\":\\\"0\\\",\\\"key\\\":\\\"town\\\"},\\\"city\\\":{\\\"text\\\":\\\"宁德市\\\",\\\"value\\\":\\\"350900\\\",\\\"key\\\":\\\"city\\\"}},\\\"detail\\\":\\\"穆云乡蟾溪村22-1号\\\"}\",\"IdCardBackPic\":\"http://verify-img.cn-shanghai.img.aliyun-inc.com/f3ba1a62ddba49aba05d270e3eb38219OSS.JPG?Expires=1555397185&OSSAccessKeyId=IJ95qE4nJQY6t6Lk&Signature=ufAgkxL8cHOhRYG5hbVJ86t1KtE%3D\",\"IdCardFrontPic\":\"http://verify-img.cn-shanghai.img.aliyun-inc.com/e710a1309e724b9b86cf4709daa3c710OSS.JPG?Expires=1555397185&OSSAccessKeyId=IJ95qE4nJQY6t6Lk&Signature=ZOeMzU0ijIF8mTYIcKBdUFISe48%3D\",\"IdentificationNumber\":\"352202199203065151\",\"IdCardExpiry\":\"20200525\",\"IdCardStartDate\":\"20100525\",\"Sex\":\"m\"},\"RequestId\":\"2F465276-AB37-438F-A265-4CF2C5E2F912\",\"Success\":true,\"Code\":\"1\"}";
            //var reuslt = data.ToObject<MaterialsResult>();
            if (UserId > 0) {
                _redRecordService.ProductRed(UserId);
                _iSoupTaskService.TaskRecive(UserId, ETaskType.Login);
            }
            var notic = _noticeService.GetAppIndexNotice(UserId);
            //var merchantlist = _merchIntroduceService.GetAppIndexMerchIntroduceList();
            ViewData["notic"] = UserId > 0 ? notic : new notice_dto();
            //ViewData["merchantlist"] = merchantlist;
            //ViewData["hongzhuan"] = _redRecordService.GetRedAndHorsePower(1);
            // ViewData["mali"]= _redRecordService.GetRedAndHorsePower(2);
            var list = _redRecordService.GetRedAndHorsePower();
            ViewData["hongzhuan"] = (list.FirstOrDefault(s => s.type == 1) ?? new red_rank_dto());
            ViewData["mali"] = (list.FirstOrDefault(s => s.type == 2) ?? new red_rank_dto());
            ViewData["user_red"] = UserId > 0 ? _redRecordService.GetUser(UserId) : new red_user_dto();
            ViewData["person"] = UserId > 0 ? _redRecordService.GetUserRed(UserId) : new user_red_dto();
            ViewData["red"] = UserId > 0 ? _redRecordService.GetRedRecordDetails(UserId) : new List<redrecorddetail_dto>();
            merch_advertisement_query_type query = new merch_advertisement_query_type();
            query.position_type = (int)EAdvertisementPositionType.IndexBanner;
            ViewData["adList"] = _iAdvertisementService.AppGetAdvertisementList(query);
            ViewData["site_img"] = RequestMethod.token_imgurl;
            ViewData["new_ad_list"] = _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = (int)EAdvertisementPositionType.IndexV2Ad, is_type = false });
            return View();
        }
        [HttpPost]
        public JsonResult GetRed(long Id) {
            var result = _redRecordService.ReciveRed(Id, UserId);
            if (result) {
                return Json(ResultToJson.Json("领取成功", true), JsonRequestBehavior.AllowGet);
            } else {
                return Json(ResultToJson.Json("领取失败", false), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 密码登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login() {
            return View("TokenLogin");
        }
        /// <summary>
        /// 密码登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult LoginByPwd(edit_password model) {
            if (!ModelState.IsValid)
                return Json(ResultToJson.Json<bool>(ModelError));
            model.oem_no = t_RequestMethod.merchant_no;
            var member = _merchantService.Login(model.mobile, model.password, model.oem_no);
            if (member != null) {
                var formsCookie = new FormsCookie();
                formsCookie.FormsCookieSave(member.name, new userCookie { roles = new List<string> { "Member" }, user_id = member.id }, true);
                return Json(ResultToJson.Json("登录成功", true), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json(1001, "登录失败", false), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 短信登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult LoginCode() {
            return View("TokenLogin");
        }
        ///// <summary>
        ///// 短信登录
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //[HttpPost, AllowAnonymous]
        //public JsonResult LoginByCode(token_login_model model) {
        //    if (!ModelState.IsValid)
        //        return Json(ResultToJson.Json<bool>(ModelError));
        //    var member = _merchantService.TokenLoginByCode(model);
        //    if (member != null) {
        //        var formsCookie = new FormsCookie();
        //        formsCookie.FormsCookieSave(member.name, new userCookie { roles = new List<string> { "Member" }, user_id = member.id }, true);
        //        return Json(ResultToJson.Json("登录成功", true), JsonRequestBehavior.AllowGet);
        //    }
        //    return Json(ResultToJson.Json(1001, "登录失败", false), JsonRequestBehavior.AllowGet);
        //}


        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Forget() {
            return View();
        }
        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult ForgetPwd(token_forget_model model) {
            if (!ModelState.IsValid)
                return Json(ResultToJson.Json<bool>(ModelError));
            _settingService.ValidCode(model.mobile, model.code, "token_forget");
            bool flag = _merchantService.Forget(new forget_model {
                code = model.code, mobile = model.mobile, mobile_code = model.mobile_code,
                oem_no = t_RequestMethod.merchant_no, password = model.password, re_password = model.re_password
            });
            if (flag)
                _settingService.RemoveCode(model.mobile, "token_forget");
            return Json(ResultToJson.Json(flag ? 1000 : 1001, flag ? "重置密码成功" : "重置密码失败", flag), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult RegisterAsync(token_register_model model) {
            if (!ModelState.IsValid)
                return Json(ResultToJson.Json<bool>(ModelError));
            var member = _merchantService.TokenRegister2Async(model);
            bool flag = member != null ? true : false;
            return Json(ResultToJson.Json(flag ? 1000 : 1001, flag ? "注册成功" : "注册失败", flag), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Register() {
            return View();
        }
        /// <summary>
        ///   邀请注册
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult InvitationRegister(long? m) {
            string invitation_code = string.Empty;
            if (m.HasValue) {
                var redcord = _redRecordService.GetUser(m.Value);
                invitation_code = redcord.invitation_code;
            }
            ViewBag.invitationCode = invitation_code;
            return View();
        }
        public ActionResult AboutUs() {
            ViewBag.ServicePhone = _settingService.GetTokenSetting().app.service_phone;
            return View();
        }

        public ActionResult Set() {
            return View();
        }
        [AllowAnonymous]
        public ActionResult Red() { return View(); }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult GetCode(open_send_model model) {
            if (!ModelState.IsValid)
                return Json(ResultToJson.Json<bool>(ModelError));
            if (string.IsNullOrEmpty(model.mobile_code)) model.mobile_code = "86";

            bool r = VerifyCode.IsVerify(RequestMethod.DAPP_ID, RequestMethod.DAPP_KEY, model.code);
            if (!r) return Json(ResultToJson.Json<bool>("图形验证码不正确"), JsonRequestBehavior.AllowGet);

            var sendmodel = new send_model();
            var result = _settingService.SendTokenRegsms(model, ESMSVerificationCodeSource.WebPage);

            if (result == "0") {
                return Json(ResultToJson.Json("发送成功，请注意查收", true), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json<bool>("发送失败"), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="Mobile"></param>
        /// <param name="Vcode"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public JsonResult LoginPost(string Mobile, string Vcode) {
            var member = _merchantService.TokenLogin(Mobile, Vcode);
            if (member != null) {
                var formsCookie = new FormsCookie();
                formsCookie.FormsCookieSave(member.name, new userCookie { roles = new List<string> { "Member" }, user_id = member.id }, true);
                return Json(ResultToJson.Json("登录成功", true), JsonRequestBehavior.AllowGet);
            }
            return Json(ResultToJson.Json<bool>("登录失败"), JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public RedirectResult Logout(string return_url) {
            FormsAuthentication.SignOut();
            if (!string.IsNullOrEmpty(return_url))
                return Redirect(return_url);
            return Redirect("/home/index");
        }
        [AllowAnonymous]
        public ActionResult DownLoad() {
            ViewBag.app = _settingService.GetTokenSetting().app;
            return View();
        }
        /// <summary>
        /// 实人认证结果
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> FaceResult() {
            var data = await _merchantService.GetVerifyStatus(UserId);
            return View(data);
        }
        /// <summary>
        /// 验证声明
        /// </summary>
        /// <returns></returns>
        public ActionResult FaceExplain() {
            return View();
        }
        /// <summary>
        /// 实人认证支付
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Pay() {
            var api_result = new ApiResultMessage { result_msg = "操作成功" };
#if DEBUG
            api_result.result_msg = "";
            api_result.result_code = 1000;
            //var model = _iOrderService.GetFaceMall(UserId, GetHostAddress());
            //var result = await HChannelApi.Current.PostApi<mall_h5_result>(model);
            //if (result == null) {
            //    throw new ServerErrorException("网络异常");
            //}
            //if (result.result_code == 1000) {
            //    api_result.result_msg = result.code_url;
            //    api_result.result_code = 1000;
            //} else {
            //    throw new ServerErrorException(result.result_msg);
            //}
#else
            var model = _iOrderService.GetFaceMall(UserId, GetHostAddress());
            var result = await HChannelApi.Current.PostApi<mall_h5_result>(model);
            if (result == null) {
                throw new ServerErrorException("网络异常");
            }
            if (result.result_code == 1000) {
                api_result.result_msg = result.code_url;
                api_result.result_code = 1000;
            } else {
                throw new ServerErrorException(result.result_msg);
            }
#endif
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
    }
}
